import {
  request
} from "../../utils/request";
import {
  sendMessageCode,
  imageCodeVerify
} from "../../api/msgCodeController";
import {
  BASE_API
} from "../../utils/config";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: BASE_API,
    api: '',
    userLoginState: '',
    tempAvatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
    defaultAvatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
    tempNickName:'',
    formList: [
    {
      name: '手机号',
      icon: 'iconshoujihao',
      value: '',
      maxlength: '11'
    },
      {
        name: '图片验证码',
        icon: 'icontupian',
        value: '',
        maxlength: '4'
      },
      {
        name: '短信验证码',
        icon: 'iconduanxin',
        value: '',
        maxlength: "6"
      },
    ],

    count: -1, //0  重新获取     -1获取验证码         >0秒再获取
    getCode: '', //获取短信验证码
    timer: null, //定时器

    random: Math.random()
  },
  onLoad(options) {

  },
  onShow() {
    this.setData({
      api: BASE_API,
      userLoginState: wx.getStorageSync('userLoginState')
    })
  },
  /**
   * 切换图片验证码
   */
  changeRandomTime() {
    this.setData({
      random: Math.random()
    })
  },
  /**
   * 获取验证码
   */
  getYZM() {
    let c = this.data.formList[0].value
    let d = this.data.formList[1].value
    var mobileReg = /^1\d{10}$/; //手机号码正则
    if (c == null || c == '') {
      wx.showToast({
        icon: 'none',
        mask: false,
        duration: 1500,
        title: '手机号不能为空'
      })
      return false
    }
    if (!mobileReg.test(c)) {
      wx.showToast({
        icon: 'none',
        mask: false,
        duration: 1500,
        title: '请输入正确的手机号'
      })
      return
    }
    if (d == null || d == '') {
      wx.showToast({
        icon: 'none',
        mask: false,
        duration: 1500,
        title: '图片验证码不能为空！'
      })
      return false
    }
    this.sendMessageCode()
  },
  /**
   * 1.校验图片验证码
   * 2.获取短信验证码
   */
  async sendMessageCode() {
    let resolve = await imageCodeVerify({
      imgCode: this.data.formList[1].value,
    })
    if (!resolve.success) {
      wx.showToast({
        title: '图片验证码错误！',
        icon: 'none',
        mask: true,
      })
      this.setData({
        random: Math.random()
      })
    } else {
      this.countDown(60)
      let resolve = await sendMessageCode({
        mobile: this.data.formList[0].value
      })
      this.setData({
        getCode: resolve.data.code
      })
    }

  },

  /**
   * 保存表单内容
   */
  getInputValue(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      value
    } = e.detail
    this.setData({
      ['formList[' + index + '].value']: value
    })
  },
  /**
   * @description: 倒计时 TIME_COUNT秒
   */
  countDown(TIME_COUNT) {
    this.data.timer = setInterval(() => {
      TIME_COUNT--;
      if (TIME_COUNT == 0) clearInterval(this.data.timer); //如果等于0 不继续减
      this.setData({
        count: TIME_COUNT
      })
    }, 1000); //一秒减一次
  },
  /**
   * 注册按钮
   */
  register() {
    let temp = this.dataVerify()
    if (temp) {
      let yam = this.data.formList[2].value
      if (yam === this.data.getCode) {
        // 短信验证码通过
        this.registration()
        // console.log('验证码通过');
        // wx.setStorageSync('token', 'token')
        // wx.navigateBack({
        //   delta: 1,
        // })
      } else {
        // 短信验证码错误
        wx.showToast({
          title: '短信验证码错误',
          icon: 'none',
          duration: 1500,
          mask: true,
        });
        return
      }
    }
  },
  /**
   * 注册
   */
  async registration() {
    let self = this
    let bbId = wx.getStorageSync('bbId')
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    /**
     * 提示信息 一闪而过 ———— 修复
     */
    wx.request({
      url: self.data.api + '/custBaseController/registration' + '?userLoginState=' + wx.getStorageSync('userLoginState'),
      data: {
        nickName: self.data.tempNickName,
        headImgUrl: self.data.tempAvatarUrl,
        mobile: self.data.formList[0].value,
        bbId: bbId,
        code: self.data.formList[2].value
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      success: (res) => {
        let resolve = res.data
        wx.hideLoading()
        if (resolve.success) {
          wx.showToast({
            title: '注册成功！',
            success: () => {
              wx.setStorageSync('custId', resolve.data.id)
              let pages = getCurrentPages(); //获取页面栈
              let prevPage = pages[pages.length - 2]; //上一个页面
              //直接调用上一个页面的setData()方法，把数据存到上一个页面pages/index/index/index中去
              prevPage.setData({
                custId: wx.getStorageSync('custId'),
                wxlogin: true
              })
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                })
              }, 1500);
            }
          })
        } else {
          wx.showToast({
            title: resolve.errorMessage,
            icon: 'none',
          })
        }
      }
    })
    // let resolve = await request('/custBaseController/registration','POST',{
    //   mobile: this.data.formList[0].value,
    //   bbId: bbId,
    //   code: this.data.formList[2].value
    // })
    // if (resolve.success) {
    //   wx.showToast({
    //     title: '注册成功！',
    //     success:()=>{
    //       wx.setStorageSync('custId', resolve.data.id)
    //       let pages = getCurrentPages();//获取页面栈
    //       let prevPage = pages[pages.length - 2]; //上一个页面
    //       //直接调用上一个页面的setData()方法，把数据存到上一个页面pages/index/index/index中去
    //       prevPage.setData({
    //         custId: wx.getStorageSync('custId'),
    //         wxlogin: true 
    //       })
    //       setTimeout(() => {
    //         wx.navigateBack({
    //           delta: 1,
    //         })
    //       }, 1500);
    //     }
    //   })
    // }else{
    //   // wx.showToast({
    //   //   title: resolve.errorMessage,
    //   //   icon: 'error'
    //   // })
    // }
  },
  /**
   * 表单验证
   */
  dataVerify() {
    var c = this.data.formList[0].value
    var d = this.data.formList[1].value
    var e = this.data.formList[2].value
    var mobileReg = /^1\d{10}$/; //手机号码正则

    
    if (this.data.tempAvatarUrl == this.data.defaultAvatarUrl) {
      wx.showToast({
        title: '请更新头像',
        icon: 'none'
      })
      return false
    }
    if (this.data.tempNickName == '微信用户' || this.data.tempNickName == '') {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return false
    }
    
    if (c == null || c == '') {
      wx.showToast({
        icon: 'none',
        mask: false,
        duration: 1500,
        title: '手机号不能为空'
      })
      return false
    }
    if (!mobileReg.test(c)) {
      wx.showToast({
        icon: 'none',
        mask: false,
        duration: 1500,
        title: '请输入正确的手机号'
      })
      this.dataValid = false;
      return false
    }
    if (d == null || d == '') {
      wx.showToast({
        icon: 'none',
        mask: false,
        duration: 1500,
        title: '图片验证码不能为空'
      })
      return false
    }
    if (e == null || e == '') {
      wx.showToast({
        icon: 'none',
        mask: false,
        duration: 1500,
        title: '短信验证码不能为空'
      })
      return false
    }
    return true
    

  },


       
  showLogin(e){
    this.setData({
      popupLoginVisible:true,
    })
  },

  setLogin(e){
    if (this.data.tempAvatarUrl == this.data.defaultAvatarUrl) {
      wx.showToast({
        title: '请更新头像',
        icon: 'none'
      })
      return
    }
    if (this.data.tempNickName == '微信用户' || this.data.tempNickName == '') {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }
    this.setData({
      popupLoginVisible:false,
    })
  },


  /**
   * 输入框
   */
  onInput(e){
    console.log(e)
    let  nickName  = e.detail.value
    console.log("==当前昵称:"+nickName)
      this.setData({
        tempNickName : nickName
      })
    },

    onChooseAvatar(e){
      let that = this
       return new Promise((resolve, reject) => {
         wx.uploadFile({
           url: that.data.baseUrl + '/uploadAvatar',
           name: 'avatarUrl',
           filePath: e.detail.avatarUrl,
           header: {
             'content-type': ' multipart/form-data',
           },
           success: res => {
             console.log("服务器保存头像的位置:"+res.data)
             this.setData({
               tempAvatarUrl:res.data,
             })
   
           },  
           fail: res => {
             wx.showToast({
               title: '上传失败',
               icon: 'none',
               duration: 2000,
             })
           }
         })
       })
      },



})